package cn.lili.modules.promotion.serviceimpl;

import cn.lili.common.utils.StringUtils;
import cn.lili.modules.promotion.entity.BlindboxRelVO;
import cn.lili.modules.promotion.entity.dos.BlindboxRel;
import cn.lili.modules.promotion.entity.dos.BlindboxRule;
import cn.lili.modules.promotion.entity.vos.BlindboxRuleVO;
import cn.lili.modules.promotion.mapper.BlindboxRelMapper;
import cn.lili.modules.promotion.mapper.BlindboxRuleMapper;
import cn.lili.modules.promotion.service.BlindboxRelService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 盲盒规则商品关联 业务实现
 *
 * @author xiangqian
 */
@Service
@RequiredArgsConstructor
public class BlindboxRelServiceImpl extends ServiceImpl<BlindboxRelMapper, BlindboxRel> implements BlindboxRelService {

    @Resource
    private BlindboxRuleMapper blindboxRuleMapper;

    /**
     * 根据商品ID查询盲盒规则
     *
     * @param goodsId 商品ID
     * @return 规则ID
     */
    @Override
    public String getRuleIdByGoodsId(String goodsId) {
        if (StringUtils.isEmpty(goodsId)) {
            return null;
        }

        QueryWrapper<BlindboxRel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goods_id", goodsId);
        queryWrapper.eq("delete_flag", false);
        queryWrapper.last("limit 1");
        BlindboxRel blindboxRel = this.baseMapper.selectOne(queryWrapper);
        return blindboxRel != null ? blindboxRel.getRuleId() : null;
    }

    @Override
    public Boolean addBlindboxRel(BlindboxRelVO blindboxRelVO) {
        //检索关联关系是否已经存在
        LambdaQueryWrapper<BlindboxRel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BlindboxRel::getGoodsId,blindboxRelVO.getGoodsId());
        queryWrapper.eq(BlindboxRel::getRuleId,blindboxRelVO.getRuleId());
        List<BlindboxRel> list = this.baseMapper.selectList(queryWrapper);
        if(list!=null&&list.size()>0){
            return false;
        }

        //新增关系
        BlindboxRel blindboxRel = new BlindboxRel();
        BeanUtils.copyProperties(blindboxRelVO, blindboxRel);
        this.baseMapper.insert(blindboxRel);

        //查询规则
        BlindboxRule blindboxRule = blindboxRuleMapper.selectById(blindboxRelVO.getRuleId());
        if(blindboxRule != null){
            blindboxRule.setIsUse(true);
            blindboxRuleMapper.updateById(blindboxRule);
        }
        return true;
    }
}